<?php
// +—————————————————————————————————————————————————————————————————————
// | Created by Yunbao
// +—————————————————————————————————————————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +—————————————————————————————————————————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +—————————————————————————————————————————————————————————————————————
// | Date: 2022-04-30
// +—————————————————————————————————————————————————————————————————————

	/* Redis链接 */
	function connectionRedis(){
		$REDIS_HOST= DI()->config->get('app.REDIS_HOST');
		$REDIS_AUTH= DI()->config->get('app.REDIS_AUTH');
		$REDIS_PORT= DI()->config->get('app.REDIS_PORT');
		$redis = new Redis();
		$redis -> pconnect($REDIS_HOST,$REDIS_PORT);
		$redis -> auth($REDIS_AUTH);

		DI()->redis=$redis;
	}
	/* 设置缓存 */
	function setcache($key,$info){
		$config=getConfigPri();
		if($config['cache_switch']!=1){
			return 1;
		}

		DI()->redis->set($key,json_encode($info));
		DI()->redis->expire($key, $config['cache_time']); 

		return 1;
	}	
	/* 设置缓存 可自定义时间*/
	function setcaches($key,$info,$time=0){
		DI()->redis->set($key,json_encode($info));
        if($time>0){
            DI()->redis->expire($key, $time); 
        }
		
		return 1;
	}
	/* 获取缓存 */
	function getcache($key){
		$config=getConfigPri();

		if($config['cache_switch']!=1){
			$isexist=false;
		}else{
			$isexist=DI()->redis->Get($key);
		}

		return json_decode($isexist,true);
	}		
	/* 获取缓存 不判断后台设置 */
	function getcaches($key){

		$isexist=DI()->redis->Get($key);
		
		return json_decode($isexist,true);
	}
	/* 删除缓存 */
	function delcache($key){
		$isexist=DI()->redis->del($key);
		return 1;
	}
    
	/* 去除NULL 判断空处理 主要针对字符串类型*/
	function checkNull($checkstr){
		$checkstr=urldecode($checkstr);
		$checkstr=htmlspecialchars($checkstr);
		$checkstr=trim($checkstr);
		//$checkstr=filterEmoji($checkstr);
		if( strstr($checkstr,'null') || (!$checkstr && $checkstr!=0 ) ){
			$str='';
		}else{
			$str=$checkstr;
		}
		return $str;	
	}
	
	/* 去除emoji表情 */
	function filterEmoji($str){
		$str = preg_replace_callback(
			'/./u',
			function (array $match) {
				return strlen($match[0]) >= 4 ? '' : $match[0];
			},
			$str);
		return $str;
	}
    

	/* 检验手机号 */
	function checkMobile($mobile){

		$ismobile = preg_match("/^1[3|4|5|6|7|8|9]\d{9}$/",$mobile);
		if($ismobile){
			return 1;
		}else{
			return 0;
		}
	}
	/* 随机数 */
	function random($length = 6 , $numeric = 0) {
		PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
		if($numeric) {
			$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
		} else {
			$hash = '';
			$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
			$max = strlen($chars) - 1;
			for($i = 0; $i < $length; $i++) {
				$hash .= $chars[mt_rand(0, $max)];
			}
		}
		return $hash;
	}	

	
	function Post($curlPost,$url){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_NOBODY, true);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
		$return_str = curl_exec($curl);
		curl_close($curl);
		return $return_str;
	}
	
	function xml_to_array($xml){
		$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
		if(preg_match_all($reg, $xml, $matches)){
			$count = count($matches[0]);
			for($i = 0; $i < $count; $i++){
			$subxml= $matches[2][$i];
			$key = $matches[1][$i];
				if(preg_match( $reg, $subxml )){
					$arr[$key] = xml_to_array( $subxml );
				}else{
					$arr[$key] = $subxml;
				}
			}
		}
		return $arr;
	}

    
    /* 发送验证码 -- 阿里云 */
	function sendCode($country_code,$mobile,$code){
        
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
        
		$config = getConfigPri();
        
        if(!$config['sendcode_switch']){
            $rs['code']=667;
			$rs['msg']='123456';
            return $rs;
        }
        
  
		$rs=sendCodeByAli($country_code,$mobile,$code);
		


		return $rs;
	}



	//阿里云短信
	function sendCodeByAli($country_code,$mobile,$code){
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
        
        $configpri = getConfigPri();

        //判断是否是国外
        $aly_sendcode_type=$configpri['aly_sendcode_type'];
        if($aly_sendcode_type==1 && $country_code!=86){ //国内
        	$rs['code']=1002;
			$rs['msg']="平台短信仅支持中国大陆地区";
            return $rs;
        }

        if($aly_sendcode_type==2 && $country_code==86){
        	$rs['code']=1002;
			$rs['msg']='平台短信仅支持国际/港澳台地区';
			return $rs;
        }
		
		require_once API_ROOT.'/../sdk/aliyunsms/AliSmsApi.php';

		$config_dl  = array(
            'accessKeyId' => $configpri['aly_keyid'], 
            'accessKeySecret' => $configpri['aly_secret'], 
            'PhoneNumbers' => $mobile, 
            'SignName' => $configpri['aly_signName'], //国内短信签名 
            'TemplateCode' => $configpri['aly_templateCode'], //国内短信模板ID
            'TemplateParam' => array("code"=>$code) 
        );

        $config_hw  = array(
            'accessKeyId' => $configpri['aly_keyid'], 
            'accessKeySecret' => $configpri['aly_secret'], 
            'PhoneNumbers' => $country_code.$mobile, 
            'SignName' => $configpri['aly_hw_signName'], //港澳台/国外短信签名 
            'TemplateCode' => $configpri['aly_hw_templateCode'], //港澳台/国外短信模板ID
            'TemplateParam' => array("code"=>$code) 
        );
        
		if($aly_sendcode_type==1){ //国内
            $config=$config_dl;
        }else if($aly_sendcode_type==2){ //国际/港澳台地区
            $config=$config_hw;
        }else{

            if($country_code==86){
                $config=$config_dl;
            }else{
                $config=$config_hw;
            }
        }
		 
		$go = new \AliSmsApi($config);
		$result = $go->send_sms();
		file_put_contents(API_ROOT.'/../log/sendCode_aly_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 result:'.json_encode($result)."\r\n",FILE_APPEND);
		
        if($result == NULL ) {
            $rs['code']=1002;
			$rs['msg']="发送失败";
            return $rs;
        }
		if($result['Code']!='OK') {
            //TODO 添加错误处理逻辑
            $rs['code']=1002;
			$rs['msg']="获取失败";
            return $rs;
        }
		return $rs;
	}


	/* 检测文件后缀 */
	function checkExt($filename){
		$config=array("jpg","png","jpeg");
		$ext   =   pathinfo(strip_tags($filename), PATHINFO_EXTENSION);
		 
		return empty($config) ? true : in_array(strtolower($ext), $config);
	}	    
	
	/* 密码检查 */
	function passcheck($user_pass) {
		$num = preg_match("/^[a-zA-Z]+$/",$user_pass);
		$word = preg_match("/^[0-9]+$/",$user_pass);
		$check = preg_match("/^[a-zA-Z0-9]{6,12}$/",$user_pass);
		if($num || $word ){
			return 2;
		}else if(!$check){
			return 0;
		}		
		return 1;
	}
	
	/* 密码加密 */
	function setPass($pass){
		$authcode='rCt52pF2cnnKNB3Hkp';
		$pass="###".md5(md5($authcode.$pass));
		return $pass;
	}	
	
	/* 公共配置 */
	function getConfigPub() {
		$key='getConfigPub';
		$config=getcaches($key);

		if(!$config){
			$config= DI()->notorm->option
					->select('option_value')
					->where("option_name='site_info'")
					->fetchOne();
            $config=json_decode($config['option_value'],true);
			setcaches($key,$config);
		}

		if(is_array($config['login_type'])){
            
        }else if($config['login_type']){
            $config['login_type']=preg_split('/,|，/',$config['login_type']);
        }else{
            $config['login_type']=array();
        }
        
        if(is_array($config['share_type'])){
            
        }else if($config['share_type']){
            $config['share_type']=preg_split('/,|，/',$config['share_type']);
        }else{
            $config['share_type']=array();
        }
        
        $config['watermark']=get_upload_path($config['watermark']);
        
		return 	$config;
	}		
	
	/* 私密配置 */
	function getConfigPri() {
		$key='getConfigPri';
		$config=getcaches($key);

		if(!$config){
			$config= DI()->notorm->option
					->select('option_value')
					->where("option_name='configpri'")
					->fetchOne();
            $config=json_decode($config['option_value'],true);
			setcaches($key,$config);
		}
        
		return 	$config;
	}		
	
	/**
	 * 返回带协议的域名
	 */
	function get_host(){
		$config=getConfigPub();
		return $config['site'];
	}	
	
	/**
	 * 转化数据库保存的文件路径，为可以访问的url cloudtype:云存储方式 0 本地 1 七牛云 2 腾讯云
	 */
	function get_upload_path($file){

        if($file==''){
            return $file;
        }

        $configpri=getConfigPri();

		if(strpos($file,"http")===0){

			//将字符串分隔
			$file_arr=explode('%@%cloudtype=',$file);
		
			$cloudtype=$file_arr['1'];
			$file=$file_arr['0'];

			if(!isset($cloudtype)){
				return html_entity_decode($file);
			}


		
			
			if(strpos($file,"http")===0){
				return html_entity_decode($file_arr['0']);
			}else if($cloudtype==1){ //存储方式为七牛
				return html_entity_decode($file);
			}else {
				return html_entity_decode($file);
			}
	
			
		}else if(strpos($file,"/")===0){

			$filepath= get_host().$file;
			return html_entity_decode($filepath);

		}else{
			//$space_host= DI()->config->get('app.Qiniu.space_host');
			//$filepath=$space_host."/".$file;

			//将字符串分隔
			$file_arr=explode('%@%cloudtype=',$file);

			$cloudtype=$file_arr['1'];
			$file=$file_arr['0'];

			if($cloudtype==1){ //七牛存储
				$space_host=$configpri['qiniu_protocol']."://".$configpri['qiniu_domain']."/";
			}else{
				$space_host="http://";
			}
			
			$filepath=$space_host.$file;

			if(!isset($cloudtype)){
				return html_entity_decode($filepath);
			}

			if($cloudtype==2 && $configpri['tx_private_signature']){ //腾讯云存储 且 需要签名验证
				return setTxUrl(html_entity_decode($filepath)); //腾讯云存储为私有读写时需要调用该方法获取签名验证
			}else{
				return html_entity_decode($filepath);
			}

			
		}
	}
	
	/* 判断是否关注 */
	function isAttention($uid,$touid) {

		if($touid==0){  //系统管理员直接返回1，不让用户关注系统管理员
			return "1";
		}

		if($uid<0||$touid<0){
			return "0";
		}

		$isexist=DI()->notorm->user_attention
					->select("*")
					->where('uid=? and touid=?',$uid,$touid)
					->fetchOne();
		if($isexist){
			return  '1';
		}else{
			return  '0';
		}			 
	}

	
	
	/* 判断token */
	function checkToken($uid,$token) {

		//判断用户是否存在
		$is_exist=checkUserIsExist($uid);

		if(!$is_exist){
			return 700;
		}

		$userinfo=getcaches("token_".$uid);
		if(!$userinfo){
			$userinfo=DI()->notorm->user_token
						->select('token,expire_time')
						->where('user_id = ? ', $uid)
						->fetchOne();
			
			setcaches("token_".$uid,$userinfo);
		}
		
		if($userinfo['token']!=$token || $userinfo['expire_time']<time()){

			return 700;				
		}
         
        $isBlackUser=isBlackUser($uid);         
        if($isBlackUser==0){
			return 10020;//账号被禁用
		}
			
        return 	0;				 		
	}	
	
	/* 用户基本信息 */
	function getUserInfo($uid,$tree='') {
		$info=getCache("userinfo_".$uid);
		$info=false;
		if(!$info){
			$info=DI()->notorm->user
					->select('id,user_nicename,avatar,avatar_thumb,sex,signature,province,city,area,birthday,age,user_status,bg_img')
					->where('id=? and user_type="2"',$uid)
					->fetchOne();

			if($info){

				if($info['age']<0){
					$info['age']="年龄未填写";
				}else{
					$info['age'].="岁";
				}

				if($info['city']==""){
					$info['city']="城市未填写";
				}

				if($info['user_status']==3){ //账号已注销

					$info['praise']='0';
					$info['fans']='0';
					$info['follows']='0';
					$info['workVideos']='0';
					$info['likeVideos']='0';
				

				}else{
					$info['praise']=getPraises($uid);
					$info['fans']=getFans($uid);
					$info['follows']=getFollows($uid);
					$info['workVideos']=getWorks($uid);
					$info['likeVideos']=getLikes($uid);

				}

				$info['avatar']=get_upload_path($info['avatar']);
				$info['avatar_thumb']=get_upload_path($info['avatar_thumb']);
				$info['hometown']=$info['province'].$info['city'].$info['area'];
				$info['bg_img']=get_upload_path($info['bg_img']);



			}else{

				$info['user_nicename']='用户';
				$info['avatar']=get_upload_path('/default.png');
				$info['avatar_thumb']=get_upload_path('/default_thumb.png');
				$info['sex']='0';
				$info['signature']='这家伙很懒，什么都没留下';
				$info['province']='省份未填写';
				$info['city']='城市未填写';
				$info['birthday']='';
				$info['age']="年龄未填写";
				$info['praise']='0';
				$info['fans']='0';
				$info['follows']='0';
				$info['workVideos']='0';
				$info['likeVideos']='0';

				$info['hometown']="";
				$info['hometown']="1";

				$info['bg_img']=$info['avatar'];


			}
		
		}

		if($tree){

			$info['user_nicename']=eachReplaceSensitiveWords($tree,$info['user_nicename']); //用户昵称过滤敏感词
			$info['signature']=eachReplaceSensitiveWords($tree,$info['signature']); //个性签名过滤敏感词
		}else{
			$info['user_nicename']=ReplaceSensitiveWords($info['user_nicename']); //用户昵称过滤敏感词
			$info['signature']=ReplaceSensitiveWords($info['signature']); //个性签名过滤敏感词
		}

		

		


		return 	$info;		
	}
	
	
	/* 统计 关注 */
	function getFollows($uid) {
		$count=DI()->notorm->user_attention
				->where('uid=? and touid>0 ',$uid)  //关注系统管理员不显示
				->count();
		return 	$count;
	}

	/* 统计 个人作品数 */
	function getWorks($uid) {
		$count=DI()->notorm->user_video
				->where('uid=? and isdel=0 and status=1',$uid)
				->count();
		return 	$count;
	}

	/* 统计 个人喜欢其他人的作品数 */
	function getLikes($uid) {
		

		$count=DI()->notorm->user_video_like
				->where('uid=? and status=1',$uid)  //status=1表示视频状态正常，未被二次拒绝或被下架
				->count();

		return 	$count;
	}			
	
	/* 统计 粉丝 */
	function getFans($uid) {
		$count=DI()->notorm->user_attention
				->where('touid=? ',$uid)
				->count();
		return 	$count;
	}		
	/**
	*  @desc 根据两点间的经纬度计算距离
	*  @param float $lat 纬度值
	*  @param float $lng 经度值
	*/
	function getDistance($lat1, $lng1, $lat2, $lng2){
		$earthRadius = 6371000; //近似地球半径 单位 米
		 /*
		   Convert these degrees to radians
		   to work with the formula
		 */

		$lat1 = ($lat1 * pi() ) / 180;
		$lng1 = ($lng1 * pi() ) / 180;

		$lat2 = ($lat2 * pi() ) / 180;
		$lng2 = ($lng2 * pi() ) / 180;


		$calcLongitude = $lng2 - $lng1;
		$calcLatitude = $lat2 - $lat1;
		$stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);  $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
		$calculatedDistance = $earthRadius * $stepTwo;
		
		$distance=$calculatedDistance/1000;
		if($distance<10){
			$rs=round($distance,2);
		}else if($distance > 1000){
			$rs='>1000';
		}else{
			$rs=round($distance);
		}
		return $rs.'km';
	}
	/* 判断账号是否禁用 */
	function isBan($uid){
		$status=DI()->notorm->user
					->select("user_status")
					->where('id=?',$uid)
					->fetchOne();
		if(!$status || $status['user_status']==0){
			return 0;
		}
		return 1;
	}
	/* 是否认证 */
	function isAuth($uid){
		$status=DI()->notorm->user_auth
					->select("status")
					->where('uid=?',$uid)
					->fetchOne();
		if($status && $status['status']==1){
			return 1;
		}

		return 0;
	}
	/* 过滤字符 */
	function filterField($field){
		$configpri=getConfigPri();
		
		$sensitive_field=$configpri['sensitive_field'];
		
		$sensitive=explode(",",$sensitive_field);
		$replace=array();
		$preg=array();
		foreach($sensitive as $k=>$v){
			if($v){
				$re='';
				$num=mb_strlen($v);
				for($i=0;$i<$num;$i++){
					$re.='*';
				}
				$replace[$k]=$re;
				$preg[$k]='/'.$v.'/';
			}else{
				unset($sensitive[$k]);
			}
		}
		
		return preg_replace($preg,$replace,$field);
	}
	/* 时间差计算 */
	function datetime($time){
		$cha=time()-$time;
		$iz=floor($cha/60);
		$hz=floor($iz/60);
		$dz=floor($hz/24);
		/* 秒 */
		$s=$cha%60;
		/* 分 */
		$i=floor($iz%60);
		/* 时 */
		$h=floor($hz/24);
		/* 天 */
		
		if($cha<60){
			return $cha.'秒前';
		}else if($iz<60){
			return $iz.'分钟前';
		}else if($hz<24){
			return $hz.'小时前';
		}else if($dz<30){
			return $dz.'天前';
		}else{
			return date("Y-m-d",$time);
		}
	}

	/* 时长格式化 */
	function getSeconds($time,$type=0){

		if(!$time){
			return (string)$time;
		}

	    $value = array(
	      "years"   => 0,
	      "days"    => 0,
	      "hours"   => 0,
	      "minutes" => 0,
	      "seconds" => 0
	    );

	    if($time >= 31556926){
	      $value["years"] = floor($time/31556926);
	      $time = ($time%31556926);
	    }
	    if($time >= 86400){
	      $value["days"] = floor($time/86400);
	      $time = ($time%86400);
	    }
	    if($time >= 3600){
	      $value["hours"] = floor($time/3600);
	      $time = ($time%3600);
	    }
	    if($time >= 60){
	      $value["minutes"] = floor($time/60);
	      $time = ($time%60);
	    }
	    $value["seconds"] = floor($time);

	    if($value['years']){
	    	if($type==1&&$value['years']<10){
	    		$value['years']='0'.$value['years'];
	    	}
	    }

	    if($value['days']){
	    	if($type==1&&$value['days']<10){
	    		$value['days']='0'.$value['days'];
	    	}
	    }

	    if($value['hours']){
	    	if($type==1&&$value['hours']<10){
	    		$value['hours']='0'.$value['hours'];
	    	}
	    }

	    if($value['minutes']){
	    	if($type==1&&$value['minutes']<10){
	    		$value['minutes']='0'.$value['minutes'];
	    	}
	    }

	    if($value['seconds']){
	    	if($type==1&&$value['seconds']<10){
	    		$value['seconds']='0'.$value['seconds'];
	    	}
	    }

	    if($value['years']){
	    	$t=$value["years"] ."年".$value["days"] ."天". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
	    }else if($value['days']){
	    	$t=$value["days"] ."天". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
	    }else if($value['hours']){
	    	$t=$value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
	    }else if($value['minutes']){
	    	$t=$value["minutes"] ."分".$value["seconds"]."秒";
	    }else if($value['seconds']){
	    	$t=$value["seconds"]."秒";
	    }
	    
	    return $t;

	}	
	
	/* 数字格式化 */
	function NumberFormat($num){
		if($num<10000){

		}else if($num<1000000){
			$num=round($num/10000,2).'w';
		}else if($num<100000000){
			$num=round($num/10000,1).'w';
		}else if($num<10000000000){
			$num=round($num/100000000,2).'y';
		}else{
			$num=round($num/100000000,1).'y';
		}


		return $num;
	}



	
	/* ip限定 */
	function ip_limit(){
		$configpri=getConfigPri();
		if($configpri['iplimit_switch']==0){
			return 0;
		}
		$date = date("Ymd");
		$ip= ip2long($_SERVER["REMOTE_ADDR"]) ; 
		
		$isexist=DI()->notorm->getcode_limit_ip
				->select('ip,date,times')
				->where(' ip=? ',$ip) 
				->fetchOne();
		if(!$isexist){
			$data=array(
				"ip" => $ip,
				"date" => $date,
				"times" => 1,
			);
			$isexist=DI()->notorm->getcode_limit_ip->insert($data);
			return 0;
		}elseif($date == $isexist['date'] && $isexist['times'] >= $configpri['iplimit_times'] ){
			return 1;
		}else{
			if($date == $isexist['date']){
				$isexist=DI()->notorm->getcode_limit_ip
						->where(' ip=? ',$ip) 
						->update(array('times'=> new NotORM_Literal("times + 1 ")));
				return 0;
			}else{
				$isexist=DI()->notorm->getcode_limit_ip
						->where(' ip=? ',$ip) 
						->update(array('date'=> $date ,'times'=>1));
				return 0;
			}
		}	
	}


	//账号是否禁用
	function isBlackUser($uid){

		$userinfo=DI()->notorm->user->where("id=".$uid." and user_status=0")->fetchOne();
		
		if($userinfo){
			return 0;//禁用
		}
		return 1;//启用


	}

	/*检测手机号是否存在*/
	function checkMoblieIsExist($mobile){
		$res=DI()->notorm->user->select("id,user_nicename,user_type")->where("mobile='{$mobile}'")->fetchOne();


		if($res){
			//判断账号是否被禁用
			if($res['user_status']==0){
				return 0;
			}else{
				return 1;
			}
		}else{
			return 0;
		}
		
	}


	/*检测手机号是否可以发送验证码*/
	function checkMoblieCanCode($mobile){
		$res=DI()->notorm->user->select("id,user_nicename,user_type,user_status")->where("mobile='{$mobile}'")->fetchOne();


		if($res){
			//判断账号是否被禁用
			if($res['user_status']==0){
				return 0;
			}else{
				return 1;
			}
		}else{
			return 1;
		}
		
	}

	/*获取用户的视频点赞总数*/
	function getPraises($uid){
		$res=DI()->notorm->user_video->where("uid=?",$uid)->sum("likes");

		if(!$res){
			$res="0";
		}	

		return $res;
	}

	/*获取音乐信息*/
	function getMusicInfo($user_nicename,$musicid){

		$res=DI()->notorm->user_music->select("id,title,author,img_url,length,file_url,use_nums")->where("id=?",$musicid)->fetchOne();

		if(!$res){
			$res=array();
			$res['id']='0';
			$res['title']='';
			$res['author']='';
			$res['img_url']='';
			$res['length']='00:00';
			$res['file_url']='';
			$res['use_nums']='0';
			$res['music_format']='@'.$user_nicename.'创作的原声';

		}else{
			$res['music_format']=$res['title'].'--'.$res['anchor'];
			$res['img_url']=get_upload_path($res['img_url']);
			$res['file_url']=get_upload_path($res['file_url']);
		}

		

		return $res;

	}

	/*距离格式化*/
	function distanceFormat($distance){
		if($distance<1000){
			return $distance.'米';
		}else{

			if(floor($distance/10)<10){
				return number_format($distance/10,1);  //保留一位小数，会四舍五入
			}else{
				return ">10千米";
			}
		}
	}

	/* 视频是否点赞 */
	function ifLike($uid,$videoid){
		$like=DI()->notorm->user_video_like
				->select("id")
				->where("uid='{$uid}' and videoid='{$videoid}'")
				->fetchOne();
		if($like){
			return 1;
		}else{
			return 0;
		}	
	}




    /* 校验签名 */
    function checkSign($data,$sign){
        //return 1;
        if($sign==''){
            return 0;
        }
        $key=DI()->config->get('app.sign_key');
        $str='';
        ksort($data);
        foreach($data as $k=>$v){
            $str.=$k.'='.$v.'&';
        }
        $str.=$key;
        $newsign=md5($str);
        
        if($sign==$newsign){
            return 1;
        }
        return 0;
    }
    
    /* 视频数据处理 */
    function handleVideo($uid,$v,$tree){
      
		$userinfo=getUserInfo($v['uid'],$tree);
		if(!$userinfo){
			$userinfo['user_nicename']="已删除";
		}

		if($v['title']){
			$v['title']=eachReplaceSensitiveWords($tree,$v['title']);
		}

		//防止uid为0时因为找不到用户信息而出现头像昵称为null的问题
		$v['user_nicename']=$userinfo['user_nicename'];
		$v['avatar']=$userinfo['avatar'];
		
		$v['userinfo']=$userinfo;
		$v['datetime']=datetime($v['addtime']);	
		$v['addtime_format']=$v['addtime'];
		$v['addtime']=date('Y-m-d H:i:s',$v['addtime']);
		
		$v['comments']=NumberFormat($v['comments']);	
		$v['likes']=NumberFormat($v['likes']);	
		$v['steps']=NumberFormat($v['steps']);
		$v['shares']=NumberFormat($v['shares']);
        
        $v['islike']='0';	
        $v['isattent']='0';
        
		if($uid>0){
			$v['islike']=(string)ifLike($uid,$v['id']);	
		}
        
        if($uid>0 && $uid!=$v['uid']){
            $v['isattent']=(string)isAttention($uid,$v['uid']);	
        }

		$v['musicinfo']=getMusicInfo($userinfo['user_nicename'],$v['music_id']);	
		$v['thumb']=get_upload_path($v['thumb']);
		$v['thumb_s']=get_upload_path($v['thumb_s']);
		$v['href']=encryption(get_upload_path($v['href']));
		$v['href_w']=encryption(get_upload_path($v['href_w']));



	
		unset($v['orderno']);
		unset($v['isdel']);
		unset($v['show_val']);

        return $v;
    }
    
    function encryption($code){
		$str = 'HmTPvkJ3otK5gp.COdrAi:q09Z62ash-QGn8V;FNIlbfM/D74Wj&S_E=UzYuw?1ecxXyLRB';
		$strl=strlen($str);
        
	   	$len = strlen($code);

      	$newCode = '';
	   	for($i=0;$i<$len;$i++){
         	for($j=0;$j<$strl;$j++){
            	if($str[$j]==$code[$i]){
               		if(($j+1)==$strl){
                   		$newCode.=$str[0];
	               	}else{
	                   	$newCode.=$str[$j+1];
	               	}
	            }
         	}
      	}
      	return $newCode;
	}	



    //过滤关键词基础方法
    function trieTreeBasic(){
    	require_once API_ROOT.'/public/TrieTree/TrieTree.php';

		//创建树
		$tree = new AbelZhou\Tree\TrieTree();

		$configpri=getConfigPri();
		$newKeywords=$configpri['sensitive_words'];

		$newKeywords=explode(",",$newKeywords);

		//向树上挂载敏感词
		foreach ($newKeywords as $keyword){
		    $tree->append($keyword);
		}



		return $tree;



    }

    //检测是否存在敏感词
    function checkSensitiveWords($str){
    	if(!$str){
    		return 0;
    	}


    	$configpri=getConfigPri();
		$newKeywords=$configpri['sensitive_words'];


		if(!$newKeywords){
			return 0;
		}

    	$tree=trieTreeBasic();

    	$res = $tree->search($str);

    	if(!$res){
    		return 0;
    	}

    	return 1;

    }


    //单条信息敏感词替换
    function ReplaceSensitiveWords($str){


    	if(!$str){
    		return "";
    	}

    	$configpri=getConfigPri();
		$newKeywords=$configpri['sensitive_words'];

		if(!$newKeywords){
			return $str;
		}

		$tree=trieTreeBasic();

    	$res = $tree->search($str);

    	if(!$res){
    		return $str;
    	}

    	foreach ($res as $k => $v) {
    		$len=mb_strlen($v['word']);
    		$replace="";
    		for ($i=0; $i <$len ; $i++) { 
    			$replace.="*";
    		}

    		$str=str_replace($v['word'],$replace,$str);
    	}


    	return $str;
    }


    //多条信息敏感词过滤【调用处需结合trieTreeBasic函数一起使用】
    function eachReplaceSensitiveWords($tree,$str){

    	$res = $tree->search($str);

    	if(!$res){
    		return $str;
    	}

    	foreach ($res as $k => $v) {
    		$len=mb_strlen($v['word']);

    		$replace=str_repeat("*",$len);

    		$str=str_replace($v['word'],$replace,$str);
    	}


    	return $str;
    }

	//判断用户是否存在
	function checkUserIsExist($uid){
		$info=DI()->notorm->user->select("user_login")->where("id=? and user_type=2",$uid)->fetchOne();
		if(!$info){
			return 0;
		}

		return 1;
	}


	//为文件拼接存储方式,方便get_upload_path做签名处理

	function setCloudType($url){
		if(!$url){
			return $url;
		}
		$configpri=getConfigPri();
		$cloudtype=$configpri['cloudtype'];

		$url=$url."%@%cloudtype=".$cloudtype;
		return $url;
	}






	
	/**
	 * 判断是否为合法的身份证号码
	 * @param $mobile
	 * @return int
	 */
	function isCreditNo($vStr){

		return true;
		
		$vCity = array(
		  	'11','12','13','14','15','21','22',
		  	'23','31','32','33','34','35','36',
		  	'37','41','42','43','44','45','46',
		  	'50','51','52','53','54','61','62',
		  	'63','64','65','71','81','82','91'
		);
		
		if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)){
		 	return false;
		}

	 	if (!in_array(substr($vStr, 0, 2), $vCity)){
	 		return false;
	 	}
	 
	 	$vStr = preg_replace('/[xX]$/i', 'a', $vStr);
	 	$vLength = strlen($vStr);

	 	if($vLength == 18){
	  		$vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
	 	}else{
	  		$vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
	 	}

		if(date('Y-m-d', strtotime($vBirthday)) != $vBirthday){
		 	return false;
		}

	 	if ($vLength == 18) {
	  		$vSum = 0;
	  		for ($i = 17 ; $i >= 0 ; $i--) {
	   			$vSubStr = substr($vStr, 17 - $i, 1);
	   			$vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
	  		}
	  		if($vSum % 11 != 1){
	  			return false;
	  		}
	 	}

	 	return true;
	}



	/* 时长格式化 */
	function secondsFormat($time){

		$now=time();
		$cha=$now-$time;

		if($cha<60){
			return '刚刚';
		}

		if($cha>=4*24*60*60){ //超过4天
			$now_year=date('Y',$now);
			$time_year=date('Y',$time);

			if($now_year==$time_year){
				return date("m月d日",$time);
			}else{
				return date("Y年m月d日",$time);
			}

		}else{

			$iz=floor($cha/60);
			$hz=floor($iz/60);
			$dz=floor($hz/24);

			if($dz>3){
				return '3天前';
			}else if($dz>2){
				return '2天前';
			}else if($dz>1){
				return '1天前';
			}

			if($hz>1){
				return $hz.'小时前';
			}

			return $iz.'分钟前';
			

		}

	}

	//检测注册
    function checkRegIpLimit($mobileid,$ip){

    	$configpri=getConfigPri();
		$same_device_ip_regnums=$configpri['same_device_ip_regnums'];
		if(!$same_device_ip_regnums){
			return 0;
		}


		//获取同一设备 同一ip下的总注册量
		$count=DI()->notorm->user->where("mobileid='{$mobileid}' and ip=?",$ip)->count();
		if($count<$same_device_ip_regnums){
			return 0;
		}

		return 1;

    }


    /* 检测用户是否存在 */
    function checkUser($where){
        if($where==''){
            return 0;
        }

        $isexist=DI()->notorm->user->where($where)->fetchOne();
        
        if($isexist){
            return 1;
        }
        
        return 0;
    }
